import { setUser } from '@entities/User/model/slice/userSlice'
import { useGetCurrentUserQuery } from '@shared/api/usersApi'
import { AuthContext } from '@shared/lib/context/AuthContext'
import { useAppDispatch } from '@shared/lib/hooks/redux'
import { ReactNode, useEffect } from 'react'

interface AuthProviderProps {
  children: ReactNode
}
export const AuthProvider = ({ children }: AuthProviderProps) => {
  const dispatch = useAppDispatch()
  const { data: user, isLoading, refetch } = useGetCurrentUserQuery()

  useEffect(() => {
    if (user) {
      dispatch(setUser(user))
    }
  }, [user])
  if (isLoading) {
    return null
  }
  return <AuthContext.Provider value={{ refetch, user }}>{children}</AuthContext.Provider>
}
